package com.design.handler;

import com.design.constant.Constants;
import com.design.domain.exception.NotPermissionException;
import com.design.domain.exception.ServiceException;
import com.design.domain.result.CommonResult;
import com.design.util.CodeUtil;
import com.design.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author ruoyi
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 权限码异常
	 */
	@ExceptionHandler(NotPermissionException.class)
	public CommonResult handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		System.out.println("请求地址xxx,权限码校验失败");
		log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage());
		return CommonResult.error(CodeUtil.ERROR_CODE_2, "没有访问权限，请联系管理员授权");
	}

	/**
	 * 请求方式不支持
	 */
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public CommonResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
	                                                        HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
		return CommonResult.error(e.getMessage());
	}

	/**
	 * 业务异常
	 */
	@ExceptionHandler(ServiceException.class)
	public CommonResult handleServiceException(ServiceException e, HttpServletRequest request) {
		log.error(e.getMessage(), e);
		Integer code = e.getCode();
		return StringUtils.isNotNull(code) ? CommonResult.error(code, e.getMessage()) : CommonResult.error(e.getMessage());
	}

	/**
	 * 拦截未知的运行时异常
	 */
	@ExceptionHandler(RuntimeException.class)
	public CommonResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',发生未知异常.", requestURI, e);
		return CommonResult.error(e.getMessage());
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(Exception.class)
	public CommonResult handleException(Exception e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',发生系统异常.", requestURI, e);
		return CommonResult.error(e.getMessage());
	}
}
